import random
import threading
from threading import Thread
import time

# 主函数
def main():
    print_info('entered.')
    threads: list[Thread] = []
    for i in range(5):
        threads.append(start_thread())
    for thread in threads:
        thread.join()
    print_info('exited.')

# 创建线程
def start_thread() -> Thread:
    sleep_time: int = int(random.random()*10)
    thread: Thread = Thread(target=task, args=(sleep_time,))
    thread.start()
    return thread

# 任务
def task(sleep_time: int) -> None:
    print_info(f'entered. It will sleep {sleep_time} seconds.')
    time.sleep(sleep_time)
    print_info('exited.')

# 打印消息，包括当前时间与线程信息
def print_info(info: str) -> None:
    current_thread: Thread = threading.current_thread()
    print(f'{get_current_time()}\t{current_thread.name}({current_thread.ident})\t{info}\n')

# 获取当前时间
def get_current_time() -> str:
    now_secs: float = time.time()
    now: time.struct_time = time.localtime(now_secs)
    ms: str = str(now_secs % 1)[1:]
    return f'{now.tm_year}-{now.tm_mon}-{now.tm_mday} {now.tm_hour}:{now.tm_min}:{now.tm_sec}{ms}'

if __name__ == '__main__':
    main()
